package com.xuzimian.globaldemo.spring.springmvc.controller;

import com.google.common.collect.Lists;
import com.xuzimian.globaldemo.spring.springmvc.exception.UserNameNotMatchPasswordException;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;

/**
 * @CrossOrigin 在类级别上使用，类上所有方法启用跨域请求支持
 */
@CrossOrigin(maxAge = 3600)
@Controller
@RequestMapping(value = "/home")
public class HomeController implements EnvironmentAware {

    Environment environment = null;

    /**
     * 实现 EnvironmentAware 接口方法可自动获取Environment 对象，该对象是系统环境，
     * 封装了ServletContext,ServletConfig,JndiProperty,系统环境变量和系统属性，
     * 这些都封装在propertySource属性下。
     *
     * @param environment
     */
    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    @CrossOrigin("http://domain2.com") //@CrossOrigin 注解用于在控制器方法上启用跨域请求
    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public String index() {
        return "hello Web";
    }


    @RequestMapping(value = "/getlist", method = RequestMethod.GET)
    @ResponseBody
    public List<String> getList() {
        List<String> result = Lists.newArrayList();
        result.add("aaa");
        result.add("vbbb");
        result.add("ccc");
        return result;
    }

    /**
     * 测试自定义异常自动捕获解析
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/testerror/{Id}", method = RequestMethod.GET)
    public String getList(@PathVariable("Id") long id) {
        if (id > 10) {
            throw new UserNameNotMatchPasswordException();
        }
        return "success";
    }


    /**
     * 返回test.jsp
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "/{Id}", method = RequestMethod.GET)
    public String redirectToTest(@PathVariable("Id") long id, Model model) {
        model.addAttribute("Title", "id");
        model.addAttribute("END", "hello,这是从/home/id 跳转过来的");
        return "test";
    }

    /**
     * 直接访问test.jsp
     *
     * @return
     */
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String test(Model model) {
        model.addAttribute("Title", "test");
        model.addAttribute("END", "hello,这是从/home/test 跳转过来的");
        return "test";
    }

    /**
     * 跳转到test.jsp
     *
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/redirect")
    public String redirectToTest2(Model model) throws Exception {
        model.addAttribute("Title", "redirect");
        model.addAttribute("END", "hello,这是从/home/redirect 跳转过来的");
        return "redirect:/home/test";
    }

}
